package com.example.system.controller;

import com.example.common.utils.ApiResponse;
import com.example.security.utils.JwtUtils;
import com.example.system.entity.User;
import com.example.system.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/auth")
@Tag(name = "用户管理", description = "用户注册、登录及管理接口")
public class AuthController {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;

    public AuthController(UserService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }
    @Operation(
            summary = "用户登录",
            description = "使用用户名密码获取JWT Token"
    )
    @PostMapping("/login")
    public ApiResponse<String> login(@RequestBody User user) {
        User dbUser = userService.findByUsername(user.getUsername());
        if (passwordEncoder.matches(user.getPassword(), dbUser.getPassword())) {
            return ApiResponse.success(JwtUtils.generateToken(dbUser.getUsername()));
        }
        throw new RuntimeException("Invalid credentials");
    }
}